package handler

import (
	"article/cache"
	"article/model"
	"article/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func UA(c *gin.Context) {
	uid := c.Query("uid")
	/*
		SELECT
		  *
		FROM
		  article15
		  LEFT JOIN uas ON article15.id = uas.aid
		WHERE
		  uas.uid = 1
	*/
	var article model.Article15
	model.DB.Table("article15").
		Joins("LEFT JOIN uas ON article15.id = uas.aid").
		Where(" uas.uid =?", uid).Find(&article)

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": article,
	})
	return
}

func UserArticle(c *gin.Context) {
	id := c.Query("id")
	var list []model.UserArticle
	if id != "" {
		model.DB.Table("article15").
			Select(
				"article15.id ArticleId",
				"user15.username Username",
				"user15.password Password",
				"article15.title Title",
				"article15.author Author",
				"article15.content Content",
			).
			Joins("LEFT JOIN user15 ON article15.uid = user15.id").
			Where("article15.id=?", id).
			Find(&list)
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "ok",
			"uid":  list,
		})
		return
	}
	model.DB.Table("article15").
		Select(
			"article15.id ArticleId",
			"user15.username Username",
			"user15.password Password",
			"article15.title Title",
			"article15.author Author",
			"article15.content Content",
		).
		Joins("LEFT JOIN user15 ON article15.uid = user15.id").
		Find(&list)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"uid":  list,
	})
	return
}

func Info(c *gin.Context) {
	uid, _ := c.Get("uid")
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"uid":  uid,
	})
	return
}
func Register(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	data := model.User15{
		Username: username,
		Password: pkg.Md5(password),
	}
	if err := model.DB.Create(&data).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "失败",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(data.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"token": token,
	})
	return
}

func Detail(c *gin.Context) {
	id, _ := strconv.Atoi(c.Query("id"))
	var list model.Article15
	redis_key := "list_detail_" + strconv.Itoa(id)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Where("id=?", id).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": list,
	})
}

func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size
	var list []model.Article15
	redis_key := "list_" + strconv.Itoa(page)
	cacheData, _ := cache.Rdb.Get(cache.Ctx, redis_key).Result()
	if cacheData == "" {
		model.DB.Offset(offset).Limit(size).Find(&list)
		jsonData, _ := json.Marshal(list)
		cache.Rdb.Set(cache.Ctx, redis_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(cacheData), &list)
	}
	var total int64
	model.DB.Model(&list).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "ok",
		"data":  list,
		"total": total,
	})
}

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不能为空",
		})
		return
	}
	redis_key := "error_" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "错误三次及以上账号已封禁两小时",
		})
		return
	}
	var user model.User15
	if err := model.DB.Where("username=?", username).First(&user).Error; err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次封禁两小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误请重新输入",
		})
		return
	}
	token := pkg.TokenHandler(strconv.Itoa(int(user.ID)))
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "登录成功",
		"token": token,
	})
	return
}
